package com.skyworth.web.admin.menu.controller;

import com.google.gson.JsonObject;
import com.skyworth.utils.Chn2Py;
import com.skyworth.web.admin.category.domain.CategoryModel;
import com.skyworth.web.admin.category.service.CategoryService;
import com.skyworth.web.admin.menu.domain.MenuModel;
import com.skyworth.web.admin.menu.form.MenuCategoryForm;
import com.skyworth.web.admin.menu.form.MenuForm;
import com.skyworth.web.admin.menu.repository.MenuRepository;
import com.skyworth.web.admin.menu.service.MenuCategoryService;
import com.skyworth.web.admin.menu.service.MenuService;
import com.skyworth.web.admin.user.domain.UserModel;
import com.skyworth.web.common.Constants;
import com.skyworth.web.common.controller.BaseController;
import com.skyworth.web.common.form.MenuCss;
import com.skyworth.web.common.form.Paginator;
import com.skyworth.web.common.service.AttachmentService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by skyworth on 2016/8/8.
 */
@Controller
@RequestMapping("/admin/menu")
public class MenuController extends BaseController {

	Logger LOG = LoggerFactory.getLogger(MenuController.class);


	@Autowired
	private MenuService menuService;

	@Autowired
	private MenuRepository menuRepository;

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private AttachmentService attachmentService;

	@Autowired
	private MenuCategoryService  menuCategoryService;

	@Autowired
	private MenuCss menuCss;

	@RequiresRoles(value={Constants.MENU_ROLE})
	@RequestMapping("")
	public String getAllMenus(@RequestParam(value="category_id",required = false)String category_id,
							  Paginator paginator, Model model) {

		UserModel userModel = currentUser();
		long store_id = 0;
		if(null != userModel){
			store_id = userModel.storeId;
		}
		JsonObject params = null;
		params = new JsonObject();
		params.addProperty("store_id", store_id);
		if(category_id != null){
			params.addProperty("category_id", category_id);
		}
		paginator.setSidx("id");
		paginator.setSord("desc");

		Page<MenuModel> page = menuService.pageMenu(params,paginator.pageRequest());
		paginator.feedToModel(page, model);

		menuCss = new MenuCss();
		menuCss.currentFanfou = "show";
		menuCss.currentFanfouMenu = "hover";
		model.addAttribute("menuCss", menuCss);
		List<CategoryModel> categoryModelList = categoryService.listCategory(params);
		model.addAttribute("categories", categoryModelList);
		model.addAttribute("user", userModel);
		return "admin/menu/menus";
	}


	@RequestMapping(value = {"new"})
	public String newAction(Model model) {
		UserModel userModel = currentUser();
		long storeId = 0;
		if(userModel!=null){
			storeId = userModel.storeId;
		}
		JsonObject params = null;
		params = new JsonObject();
		params.addProperty("store_id", storeId);

		menuCss = new MenuCss();
		menuCss.currentFanfou = "show";
		menuCss.currentFanfouMenu = "hover";
		model.addAttribute("menuCss", menuCss);
		model.addAttribute("user", userModel);

		List<CategoryModel> categoryModelList = categoryService.listCategory(params);
		model.addAttribute("categories", categoryModelList);
		return "admin/menu/menu_new";
	}


	@RequestMapping(value = {"create"}, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> create(@ModelAttribute MenuForm menuForm,
						 Model model) {
		Map<String, Object> map = new HashMap<>();
		UserModel user = currentUser();
		model.addAttribute("user", user);
		long store_id = 0;
		if(null != user){
			store_id = user.storeId;
		}else {
			map.put("valid", false);
			map.put("errorMsg", "请先登录");
			return map;
		}
		if (menuService.existMenu(menuForm.getName(),store_id)) {
			map.put("valid", false);
			map.put("errorMsg", menuForm.getName()+"已存在");
			return map;
		}
		menuForm.setStoreId(store_id);
		MenuModel menuModel = menuService.addMenu(menuForm);
		if(menuModel.id > 0){
			MenuCategoryForm menuCategoryForm = new MenuCategoryForm();
			menuCategoryForm.categoryId = menuForm.categoryId;
			menuCategoryForm.menuId = menuModel.id;
			menuCategoryService.addMenuCategory(menuCategoryForm);
			map.put("valid", true);
			map.put("url", "/admin/menu");
		}else {
			map.put("valid", false);
			map.put("errorMsg", "添加菜品失败");
		}
		return map;
	}

	@RequestMapping(value = {"{id}"}, method = RequestMethod.GET)
	public String detail(@PathVariable("id") long id, Model model) {
		menuCss = new MenuCss();
		menuCss.currentFanfou = "show";
		menuCss.currentFanfouMenu = "hover";
		MenuModel menuModel = menuService.findMenu(id);
		model.addAttribute("menuCss", menuCss);

		StringBuilder sb = new StringBuilder();
		if(menuModel.hasMenuPic()) {
			sb.append(menuModel.name);
		}else {
			sb.append("小鲜肉^_^");
		}
		sb.append("    ");
		sb.append(menuModel.unitPrice);
		sb.append("￥/");
		sb.append(menuModel.unitName);

		model.addAttribute("menu_info", sb.toString());

		model.addAttribute("menu", menuModel);
		model.addAttribute("user", currentUser());
		return "admin/menu/menu_detail";
	}

	@RequestMapping(value = {"edit/{id}"}, method = RequestMethod.GET)
	public String edit(@PathVariable("id") long id, Model model) {
		UserModel userModel = currentUser();
		long storeId = 0;
		if(userModel != null){
			storeId = userModel.storeId;
		}
		JsonObject params = null;
		params = new JsonObject();
		params.addProperty("store_id", storeId);
		menuCss = new MenuCss();
		menuCss.currentFanfou = "show";
		menuCss.currentFanfouMenu = "hover";
		MenuModel menuModel = menuService.findMenu(id);
		model.addAttribute("menuCss", menuCss);
		model.addAttribute("menu", menuModel);
		model.addAttribute("user", userModel);

		List<CategoryModel> categoryModelList = categoryService.listCategory(params);
		model.addAttribute("categories", categoryModelList);

		return "admin/menu/menu_edit";
	}

	@RequestMapping(value = {"{id}"}, method = RequestMethod.PUT)
	@ResponseBody
	public Map<String, Object> update(@PathVariable("id") long id,
						 @ModelAttribute MenuForm menuForm,
						 Model model) {
		Map<String, Object> map = new HashMap<>();
		UserModel userModel = currentUser();
		long storeId = 0;
		if(userModel != null){
			storeId = userModel.storeId;
		}else{
			map.put("valid", false);
			map.put("errorMsg", "请先登录");
			return map;
		}
		if(menuService.existMenu(menuForm.getName(), id, storeId)){
			map.put("valid", false);
			map.put("errorMsg", menuForm.getName()+"已存在");
			return map;
		}
		MenuModel menuModel = menuService.updateModel(menuForm);
		model.addAttribute("menu", menuModel);
		map.put("valid", true);
		map.put("url", "/admin/menu");
		return map;
	}

	@RequestMapping(value = {"{id}"}, method = RequestMethod.DELETE)
	@ResponseBody
	public Map<String,Object> delete(@PathVariable("id") long id,
									 HttpSession session) {
		Map<String, Object> rsp = responseMap();
		MenuModel menuModel = menuService.findMenu(id);

		if (menuModel != null) {
			menuService.delMenu(id);
			rsp.put("success", true);
		}else{
			rsp.put("success", false);
			rsp.put("message", "menu doesn't exist");
		}
		return rsp;
	}


	@RequestMapping(value = {"soldout"}, method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> soldOut(@RequestParam("menu_id") long menuId,
									  @RequestParam("sold_out") int soldOutFlag,
									 HttpSession session) {
		Map<String, Object> rsp = responseMap();
		int flag = 0;
		if(soldOutFlag==0){
			flag=1;
		}

		int ret  = menuService.soldOutToggle(menuId, flag);
		if(ret <= 0) {
			rsp.put("success", false);
			rsp.put("message", "result " + ret);
		}
		return rsp;
	}


	@RequestMapping(value = {"update_initial"}, method = RequestMethod.GET)
	public String updateInitial() {

		List<MenuModel> menuModels = menuService.listMenu(null);
		for (MenuModel menu: menuModels) {
			System.out.println();

			String name = menu.name;
			LOG.info("update menu "+name+ " encoding is "+ Chn2Py.getEncoding(name));
			if(name==null || name.isEmpty() || name.length()>20) {
				LOG.info("update menu error name "+menu.name);
				continue;
			}
			String py = Chn2Py.chn2py(name);
			menu.firstLetter = py;
			menuRepository.save(menu);
		}

		return "redirect:/";
	}
}
